var app = getApp();
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
var inteval;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    limit: 10,
    last_value: "",
    shopname: "",
    windowHeight: 0,
    showGoodsList: false, //显示取货清单
    machineId: '', //机器id
    oid: 0, //订单id
    errorImage: app.globalData.base_url+'upload/images/errtips.png',
    orderInfo: {},
  },

  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    })

    var timestamp = Date.parse(new Date());
    this.setData({
      errorImage: app.globalData.base_url + 'upload/images/errtips.png?v=' + timestamp,
      machineId: options.machine_id,
      oid: options.oid
    });

   that.systemSet();
   // setTimeout(function() {
   //    that.openTheDoor();
   //  }, 1000)
  },

  //异常提示图片预览
  preErrorImage:function(){
    var that=this;
    wx.previewImage({
      current: that.data.errorImage, 
      urls: [that.data.errorImage]
    })
  },

   systemSet: function (e) {
      var that = this;
      api.POST({
         url: app.globalData.base_url + 'system/set',
         success: function (res) {
            if (res.data.data.task_time){
               that.setData({
                  task_time: res.data.data.task_time
               })
            }else {
               that.setData({
                  task_time:10
               })
            }

            that.openTheDoor();

         },
         fail: function (fail) {
            util.showError("网络错误，请检查网络。");

         }
      })

   },

   //重试
   // retryOpenTheDoor: function () {
   //    const machine_id = this.data.machine_id;
   //    this.openTheDoor()
   // },

  // 开门
  openTheDoor: function() {
    var that = this;
    that.setData({
      showCheck: 1
    })
     var time = this.data.task_time * 1000
     let time2 = 0;
     var timer = setTimeout(function () {
        that.setData({
           showCheck: 4
        })
        clearTimeout(timer)
     }, time)
     var timer2 = setInterval(function () {
        time2++
     }, 1000)
     if (time2 > that.data.task_time) {
        clearTimeout(timer2)
     }

    api.POST({
      params: {
        oid: that.data.oid,
        machine_id: that.data.machineId
      },
      url: app.globalData.base_url + 'shop/openDoor',
      success: function(res) {
         if (timer){
            clearTimeout(timer)
         }
         if (timer2){
            clearTimeout(timer2)
         }
         if (time2 > that.data.task_time) {
            return false
         }
        that.setData({
          showCheck: 0
        })
        if (res.data.code == '') { //门已打开
          that.setData({
            showCheck: 2
          })
          setTimeout(function() {
            that.getOrderInfo();
          }, 1500)
        } else {
          if (res.data.code == 50004 || res.data.code == 50001) { //50004:机器故障，不可开门；50001 机器不在线，不可开门，
            that.setData({
              showCheck: 4
            })
          } else if (res.data.code == 50003) { //机器故障，需要重试
            that.setData({
              showCheck: 4,
            })
          } else if (res.data.code == 50005) { //机器处于开门状态
            that.setData({
              showCheck: 5,
            })
          } else if (res.data.code ==11831){  //其他人正在操作
            wx.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              confirmText:'我知道了',
              success: function (res) {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          }else if (res.data.code == 11919) { //已存在异常订单
            wx.showModal({
              title: '提示',
              content: res.data.message,
              showCancel: false,
              success: function(res) {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          } else {
             clearTimeout(timer)
            util.showError(res.data.message)
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            }, 2000);
          }
        }
      },
      fail: function(fail) {
      //   util.showError("网络错误，请检查网络。");
      }
    })
  },

  // 重新开门扫一扫页面
  startReplenishment: function(e) {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var rest = res.result;
        if (rest.indexOf("gzjShopId?machineid") < 0) {
          util.showStatus("请扫描机器二维码");
          return;
        }
        var arr = res.result.split("?");
        var str1 = arr[1];
        var atrr1 = str1.split("&")[0];
        var machine_id = atrr1.split("=")[1];
        that.setData({
          machineId: machine_id
        })
        setTimeout(function() {
          that.openTheDoor();
        }, 1000)
      }
    })
  },

  //获取订单详情
  getOrderInfo: function() {
    var that = this;
    api.POST({
      params: {
        oid: that.data.oid,
        type: 2
      },
      url: app.globalData.base_url + 'shop/getOrderInfo',
      success: function(res) {
        if (res.data.code) {
          util.showError(res.data.message);
          return;
        } else {
          var orderInfo = res.data.data;
          var productList = res.data.data.productList;
          var numbers = 0;
          for (var i = 0; i < productList.length; i++) {
            numbers = numbers / 1 + productList[i].number / 1;
          }
          that.setData({
            orderInfo: orderInfo,
            numbers: numbers,
            showGoodsList: true
          })
          if (orderInfo.current_status == 2) {
            //机器已开门
            that.setData({
              showCheck: 0
            }) 
          } else if (orderInfo.current_status == 3) {
            //机器已关门（开始盘点）
            that.setData({
              showCheck: 6
            })
          } else if (orderInfo.current_status == 20) {
             //机器掉线
             that.setData({
                showCheck: 20
             })
          } 
           else if (orderInfo.current_status == 7) {
            //机器已盘点完成
            that.setData({
              showCheck: 0
            })
            if (orderInfo.cancel_status==0){
              util.showError('当前订单未核销');
            }
          }

          if (orderInfo.current_status == 2 || orderInfo.current_status == 3) {
            setTimeout(function() {
              that.getOrderInfo();
            }, 1500)
          }
        }
      },
      fail: function(fail) {
      //   util.showError("网络错误，请检查网络。");
      }
    })
  },

  //联系客服
  contactServiceTap: function() {
    wx.makePhoneCall({
      phoneNumber: app.globalData.service_phone
    })
  },

  stopScroll: function() {
    return false;
  },

  //继续取货（核销用户订单）
  verification: function() {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        var rest = res.result;
        if (rest.indexOf("code") < 0 || rest.indexOf("type") < 0) {
          util.showStatus("请扫描核销二维码");
          return;
        }
        var arr = res.result.split("?");
        var str1 = arr[1];
        var atrr1 = str1.split("&")[0];
        var code = atrr1.split("=")[1];
        var types = str1.split("&")[1].split("=")[1];
        that.setApiCouponsCodeDetails(code, types);
      }
    })
  },

  //请求后台，改变订单状态为已扫码
  setApiCouponsCodeDetails: function(couponsCode, couponsType) {
    var params = {
      code: couponsCode,
      type: couponsType
    }
    util.showLoading("加载中...");
    api.POST({
      url: app.globalData.base_url + 'shop/scanInfo',
      params: params,
      success: function(res) {
        wx.hideLoading();
        if (util.isEmpty(res.data.code)) {
          var oid = res.data.data.oid
          wx.redirectTo({
            url: '../orderVerification/orderVerification?oid=' + oid,
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function(res) {
        wx.hideLoading();
        util.showError("网络错误，请检查网络。");
      }
    });
  },

  //返回上一页
  toOrderList: function() {
    wx.switchTab({
      url: '/pages/business/business'
    })
  }
})